#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>

void writer(int wfd)
{
  const char* str = "hello father,I an child,I am writing!";
  char buffer[128];
  int cnt = 0;
  pid_t pid = getpid();
  while(1)
  {
    sleep(1);
    // snprintf：把指定内容写入到指定长度char数组中
    //snprintf(buffer,sizeof(buffer),"message:%s,pid:%d,count:%d\n",str,pid,cnt);
    //write(wfd,buffer,strlen(buffer));//这里不要加上'\0'
    char c = 'A';
    write(wfd,&c,1);
    cnt++;
    printf("cnt:%d\n", cnt);  
  }
}

void reader(int rfd)
{
    char buffer[1024];
    int cnt = 0;
    while(1)
    {
      sleep(1);
      ssize_t n = read(rfd,buffer,sizeof(buffer)-1);
      if(n > 0) //代表读取成功
        printf("father get a message:%s, n:%ld\n",buffer,n);
      else if(n == 0) //代表读取到文件末尾
        printf("read pipe done, read file done!\n");
      else
        break;
      cnt++;
      if(cnt == 10)
        break;
    }
    close(rfd);
    printf("read endpoint close!\n");
}

int main()
{
  printf("PIPE_BUF:%d\n",PIPE_BUF);


  //父进程创建管道
  int pipefd[2];
  int n = pipe(pipefd);
  if(n < 0) return 1;

  printf("pipefd[0]:%d,pipe[1]:%d\n",pipefd[0],pipefd[1]);//3,4
  //                                        r         w
  //父进程fork出子进程
  pid_t id = fork();
  if(id == 0)
  {
    //child:w
    close(pipefd[0]);

    writer(pipefd[1]);

    exit(0);
  }
  //father:r
  close(pipefd[1]);
  reader(pipefd[0]);
  //wait(NULL);

  int status = 0;
  pid_t rid = waitpid(id,&status,0);
  if(rid == id)
    printf("exit code:%d, exit signal:%d\n",WEXITSTATUS(status),status&0x7F);

  return 0;
}